package com.jvup.common.constant;

import android.content.Context;

import com.jvup.common.basic.StringUtil;
import com.jvup.common.utils.CacheStorageUtil;
import com.jvup.common.utils.Logger;

import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 应用及设备配置信息
 */
public final class DeviceConfigInfo {

    private static final String CACHE_KEY_REPORTED_VERSION_TAG = "REPORTED_VERSION_TAG";
    private static final String CACHE_KEY_SERVICE_PROTOCOL_VER = "SERVICE_PROTOCOL_VER";
    private static final String CACHE_KEY_PRIVACY_PROTOCOL_VER = "PRIVACY_PROTOCOL_VER";

    private static DeviceConfigInfo INFO;

    /** 当前版本号 */
    public final int versionCode;
    /** 当前版本名 */
    public final String versionName;
    /** 当前版本APP是否是第一次运行 */
    public final boolean isRunFirst;
    /** 当前版本APP运行次数统计 */
    public final int runCountNumber;

    /** 当前服务协议版本 */
    private String serviceProtocolVer;
    /** 当前隐私协议版本 */
    private String privacyProtocolVer;

    /** 消息推送状态 true:开启 false:关闭 */
    private boolean messagePushEnable;
    /** 漫画更新推送状态 true:开启 false:关闭 */
    private boolean comicUpdatePushEnable;
    /** 漫画推荐推送状态 true:开启 false:关闭 */
    private boolean recommendPushEnable;
    /** 评论推送状态 true:开启 false:关闭 */
    private boolean commentPushEnable;

    /** 客服QQ号码 */
    private String qqNumber;

    private DeviceConfigInfo(int versionCode, String versionName) {
        this.versionCode    = versionCode;
        this.versionName    = versionName;
        this.runCountNumber = CacheStorageUtil.queryInt(versionName) + 1;
        this.isRunFirst     = this.runCountNumber == 1;

        CacheStorageUtil.save(this.versionName, this.runCountNumber);
    }

    public synchronized static void init(int versionCode, String versionName) {
        INFO = new DeviceConfigInfo(versionCode, versionName);
    }

    public static DeviceConfigInfo info() {
        if(INFO == null) {
            throw new RuntimeException("没有初始化DeviceConfigInfo！！");
        }
        return INFO;
    }

    //region    #APP版本上报管理 begin
    public static boolean checkHasReportedVersion() {
        String saveVersionName    = CacheStorageUtil.queryString(CACHE_KEY_REPORTED_VERSION_TAG);
        String currentVersionName = INFO.versionName;
        Logger.d("本地历史保存 VersionName : " + saveVersionName + " | 当前 APP 实际的 VersionName : " + currentVersionName);
        return currentVersionName.equals(saveVersionName);
    }

    public static void saveReportedVersion() {
        CacheStorageUtil.save(CACHE_KEY_REPORTED_VERSION_TAG, INFO.versionName);
    }
    //endregion #APP版本上报管理 end


    //region    #APP协议版本管理 begin
    public static void updateProtocolVer(String serviceProtocolVer, String privacyProtocolVer) {
        INFO.serviceProtocolVer = serviceProtocolVer;
        INFO.privacyProtocolVer = privacyProtocolVer;
    }

    public static void saveServiceProtocolVer() {
        String serviceProtocolVer = INFO.serviceProtocolVer;
        if (serviceProtocolVer != null) {
            CacheStorageUtil.save(CACHE_KEY_SERVICE_PROTOCOL_VER, serviceProtocolVer);
        }
    }

    public static void savePrivacyProtocolVer() {
        String privacyProtocolVer = INFO.privacyProtocolVer;
        if (privacyProtocolVer != null) {
            CacheStorageUtil.save(CACHE_KEY_PRIVACY_PROTOCOL_VER, privacyProtocolVer);
        }
    }

    public static boolean checkUpdateServiceProtocolVer() {
        String protocolVer = CacheStorageUtil.queryString(CACHE_KEY_SERVICE_PROTOCOL_VER);
        if (StringUtil.isEmpty(protocolVer)) {
            return true;
        }
        return !protocolVer.equals(INFO.serviceProtocolVer);
    }

    public static boolean checkUpdatePrivacyProtocolVer() {
        String protocolVer = CacheStorageUtil.queryString(CACHE_KEY_PRIVACY_PROTOCOL_VER);
        if (StringUtil.isEmpty(protocolVer)) {
            return true;
        }
        return !protocolVer.equals(INFO.privacyProtocolVer);
    }
    //endregion #APP协议版本管理 end


    //region    #APP推送消息状态管理 begin

    private void updatePushEnableState(boolean comicUpdatePushEnable, boolean recommendPushEnable, boolean commentPushEnable) {
        this.comicUpdatePushEnable = comicUpdatePushEnable;
        this.recommendPushEnable = recommendPushEnable;
        this.commentPushEnable = commentPushEnable;
        this.messagePushEnable = comicUpdatePushEnable || recommendPushEnable || commentPushEnable;
    }

    public static void updateMessagePushEnable(boolean messagePushEnable) {
        INFO.updatePushEnableState(messagePushEnable, messagePushEnable, messagePushEnable);
    }

    public static void updateComicUpdatePushEnable(boolean comicUpdatePushEnable) {
        INFO.updatePushEnableState(comicUpdatePushEnable, INFO.recommendPushEnable, INFO.commentPushEnable);
    }

    public static void updateRecommendPushEnable(boolean recommendPushEnable) {
        INFO.updatePushEnableState(INFO.comicUpdatePushEnable, recommendPushEnable, INFO.commentPushEnable);
    }

    public static void updateCommentPushEnable(boolean commentPushEnable) {
        INFO.updatePushEnableState(INFO.comicUpdatePushEnable, INFO.recommendPushEnable, commentPushEnable);
    }

    /** 消息推送状态 true:开启 false:关闭 */
    public static boolean messagePushEnable() {
        return INFO.messagePushEnable;
    }
    /** 漫画更新推送状态 true:开启 false:关闭 */
    public static boolean comicUpdatePushEnable() {
        return INFO.comicUpdatePushEnable;
    }
    /** 漫画推荐推送状态 true:开启 false:关闭 */
    public static boolean recommendPushEnable() {
        return INFO.recommendPushEnable;
    }
    /** 评论推送状态 true:开启 false:关闭 */
    public static boolean commentPushEnable() {
        return INFO.commentPushEnable;
    }
    //endregion #APP推送消息状态管理 end


    /**
     * 通过服务器同步客服QQ号码
     * @param qqNumber 客服QQ号码
     */
    public static void qqNumberBySyncServer(String qqNumber) {
        INFO.qqNumber = qqNumber;
    }
    /**
     * @return 客服QQ号码
     */
    public static String qqNumber() {
        return INFO.qqNumber;
    }


    /**
     * 提取渠道号，这个地方需要会有解压的过程。
     * @param context 设备上下文
     * @return 如果APK包含渠道号返回渠道号，否则返回 0 ；
     */
    public static String fetchChannel(Context context) {
        String sourceDir = context.getApplicationInfo().sourceDir;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                if (entryName.startsWith("META-INF/channel")) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String[] split = ret.split("_");
        if (split != null && split.length >= 2) {
            return ret.substring(split[0].length() + 1);
        } else {
            return "0";
        }
    }

}
